import client from '@lib/client'
import DebounceSelect from '@lib/components/DebounceSelect'
import { Button, message, Modal, Space } from 'antd'
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import ReactMarkdown from 'react-markdown'

export interface ICreatePemissionButtonProps {
  refresh: () => void
  instaceId: number
}

// Usage of DebounceSelect
interface UserValue {
  key: string
  value: string
  label: string
  display: string
}

export default function CreatePermissionButton(
  props: ICreatePemissionButtonProps
) {
  const { t } = useTranslation()

  const { refresh, instaceId } = props

  const [visible, setVisible] = useState(false)
  const [isPosting, setIsPosting] = useState(false)
  const [value, setValue] = useState<UserValue[]>([])

  const handleOpen = useCallback(() => {
    setVisible(true)
  }, [])

  const handleClose = useCallback(() => {
    setVisible(false)
    setIsPosting(false)
  }, [])

  const handleSubmit = async () => {
    try {
      setIsPosting(true)
      const r = await client.getInstance().createPermission({
        user_id: value.map((item) => item.value),
        instance_id: instaceId,
      })
      if (r.status == 200) {
        message.success('Success')
        setVisible(false)
        refresh()
      }
    } finally {
      setIsPosting(false)
    }
  }

  async function fetchUserList(search: string): Promise<UserValue[]> {
    return client
      .getInstance()
      .queryUser(search)
      .then((res) => {
        let userList = [] as UserValue[]
        if (res.status == 200) {
          const users = res.data.users
          if (users) {
            userList = users.map((user) => ({
              key: user.id ?? '',
              value: user.id ?? '',
              display: user.description ?? '',
              label: user.name ?? '',
            }))
          }
        }
        return userList
      })
  }

  return (
    <>
      <Button type="primary" onClick={handleOpen}>
        {t('instance_permission.button.create_permission')}
      </Button>
      <Modal
        title={t('instance_permission.modal.create_permission.title')}
        visible={visible}
        destroyOnClose
        onCancel={handleClose}
        width={600}
        footer={
          <Space>
            <Button onClick={handleClose}>
              {t('instance_permission.modal.create_permission.close')}
            </Button>
            <Button type="primary" loading={isPosting} onClick={handleSubmit}>
              {t('instance_permission.modal.create_permission.submit')}
            </Button>
          </Space>
        }
      >
        <ReactMarkdown
          source={t('instance_permission.modal.create_permission.desc')}
        />
        <DebounceSelect
          mode="multiple"
          value={value}
          fetchOptions={fetchUserList}
          onChange={(newValue) => {
            setValue(newValue as UserValue[])
          }}
          style={{ width: '100%' }}
        />
      </Modal>
    </>
  )
}
